<?php
namespace src\logic;
use \classlib\core as C;
class lvipsquad {
	const YMAXSIZE 	 = 10;
	const YRefType   = 2;
	const MRefType   = 1;
	
	//将保护资料信息
	private static function ckey($studioid) {
		return 'guard_'.$studioid;
	}
	
	/**
	 * 设置守护信息到redis中
	 * @param int $userid
	 * @param int $studioid
	 */
	public static function set($userid, $studioid) {
		$where   = array('userid'=>$userid, 'reftype'=>2, 'stid'=>$studioid, 'status'=>1);
		$list    = C\model::load('main.pl.props')->set_mod($userid)->get_list(0, -1, $where);
		$data    = array(0, 0, $userid);
		foreach ($list as $item) {
			if ($item['refid'] == self::MRefType) {
				$data[0] = $item['expire'];
			} else {
				$data[1] = $item['expire'];
			}
		}
		//未过期则记录一下
		if ($data[1] > C\config::$nowtime || $data[0] > C\config::$nowtime) {
			$redis   = \classlib\cache::inst('redis')->inst();
			$ckey    = self::ckey($studioid);
			$redis->hSet($ckey, $userid, implode('-', $data));
		}
	}
	
	/**
	 * 获取指定用户的redis资料信息
	 * @param int $userid
	 * @param int $studioid
	 */
	public static function get($userid, $studioid) {
		$redis   = \classlib\cache::inst('redis')->inst();
		$ckey    = self::ckey($studioid);
		$value   = $redis->hGet($ckey, $userid);
		$reftype = 0;
		if ($value) {
			list($mexpire, $yexpire, $userid) = explode('-', $value);
			if ($yexpire > C\config::$nowtime) {
				$reftype = self::YRefType;
			} else if ($mexpire > C\config::$nowtime) {
				$reftype = self::MRefType;
			}
		}
		return $reftype;
	}
	
	/**
	 * 获取某个房间守护的用户列表
	 * @param int $studioid
	 * @return array
	 */
	public static function user($studioid) {
		$redis = \classlib\cache::inst('redis')->inst();
		$ckey  = self::ckey($studioid);
		$list  = $redis->hGetAll($ckey);
		//验证会员守护是否过期
		$data  = array();
		foreach ($list as $userid=>$value) {
			$reftype = 0;
			list($mexpire, $yexpire, $userid) = explode('-', $value);
			if ($yexpire > C\config::$nowtime) {
				$reftype = self::YRefType;
			} else if ($mexpire > C\config::$nowtime) {
				$reftype = self::MRefType;
			} else {
				//过期的要清理掉
				$redis->hDel($ckey, $userid);
				laccess::reset($userid, $studioid);
				continue;
			}
			$data[] = array('userid'=>$userid, 'reftype'=>$reftype);
		}
		return $data;
	}
	
	/**
	 * 获取守护的用户键值
	 * @param int $studioid
	 * @return array
	 */
	public static function uids($studioid) {
		$redis = \classlib\cache::inst('redis')->inst();
		$ckey  = self::ckey($studioid);
		$uids  = $redis->hKeys($ckey);
		return $uids;
	}
	
	/**
	 * 获取某个直播间守护总数
	 * @param int $studioid
	 * @return int
	 */
	public static function total($studioid) {
		$redis = \classlib\cache::inst('redis')->inst();
		$ckey  = self::ckey($studioid);
		$total = $redis->hLen($ckey);
		return $total;
	}
}